local floor = math.floor
local format = string.format
local print = print

local f = io.open(arg[1], "rb")
local s = f:read "*a"
f:close()
local i = 0

local function readIntBe()
	local v = s:byte(i+1) * 0x1000000 + s:byte(i+2) * 0x10000 + s:byte(i+3) * 0x100 + s:byte(i+4)
	i = i + 4
	return v
end

local function readVarSize()
	local v = s:byte(i+1)
	if v < 252 then
		i = i + 1
		return v
	end
	v = v + s:byte(i+2) * 4
	i = i + 2
	return v
end

local index = 0
local timeMs = 0
local maxPayloadSize = 0
while i < #s do
	local pos = i
	local payloadSize = readIntBe()
	i = i + 4 -- skip
	local b0, b1 = s:byte(i+1), s:byte(i+2)
	local mode = b0 >= 0x80 and "c " or b0 >= 0x60 and "cs" or " s"
	local bw
	if b0 >= 0x80 then
		local v = floor(b0 / 32) % 4
		bw = v == 0 and 4 or v == 1 and 8 or v == 2 and 12 or 20
	elseif b0 >= 0x60 then
		bw = floor(b0 / 16) % 2 == 1 and 20 or 12
	else
		local v = floor(b0 / 32) % 4
		bw = v == 0 and 4 or v == 1 and 6 or v == 2 and 8 or 12
	end
	local ch = floor(b0 / 4) % 2 == 1 and " S" or "M "
	local v = b0 % 4
	local n = v == 0 and 1 or v < 3 and 2 or b1 % 64
	local m = floor(b0 / 8) % 4
	m = b0 >= 0x80 and 1000 * (2^m) / 400 or b0 >= 0x60 and 10 * (2^(m%2)) or m == 3 and 60 or 10 * (2^m)
	local ms = n * m
	local vbrNoPad = v == 3 and floor(b1 / 64) == 2
	local j = i
	local t = {}
	if vbrNoPad then
		m = 0
		i = i + 2
		for k = 1,n-1 do
			local v = readVarSize()
			m = m + v
			t[#t+1] = format("%3X ", v)
		end
		t[#t+1] = format("%3X", payloadSize - (i - j) - m)
	elseif v == 3 and b1 >= 0 then -- cbr
		m = (payloadSize - 2) / n
		assert(m == floor(m))
		for k = 1,n do
			t[#t+1] = format("%3X ", m)
		end
		t[#t+1] = "CBR"
	elseif v == 2 then
		i = i + 2
		local v = readVarSize()
		t[#t+1] = format("%3X ", v)
		t[#t+1] = format("%3X", payloadSize - (i - j) - v)
	end
	print(format("%8X:%6d: [%3X] %s %2dkHz %s %3dms %df: %s",
		pos, index, payloadSize, mode, bw, ch, ms, n, table.concat(t)))
	i = j + payloadSize
	index = index + 1
	timeMs = timeMs + ms
	if maxPayloadSize < payloadSize then
		maxPayloadSize = payloadSize
	end
end
print "------------------------------------------------------------------------"
print(format("TotalFrames : %d - 312(PreSkip) = %d", timeMs * 48, timeMs * 48 - 312))
print(format("TotalTime   : %.3f - 0.0065(PreSkip) = %.4f sec", timeMs * 0.001, timeMs * 0.001 - 0.0065))
print(format("Time/PayLoad: %f ms", timeMs / index))
print(format("MaxPayLoad  : %X (%d) bytes (%.3f kbps)", maxPayloadSize, maxPayloadSize, maxPayloadSize * index * 8 / (timeMs * 0.001)))
print(format("HeadSize    : (%d + %d) / %d => %d (%.3f kbps)", index * 6, index * 2, #s, #s - index * 6, (#s - index * 6) * 8 / (timeMs * 0.001 - 0.0065)))
